<template>
  <div class="msg-container">
    <div class="msg-header flex-align-center">消息列表</div>
    <div class="msg-content">
      <div class="msg-box">
        <div class="msg-list">
          <div class="msg-item" v-for="(msg, i) in msgList" :key="i">{{ msg.msg }}</div>
        </div>
        <div class="empty-box"></div>
      </div>
    </div>
    <div class="msg-tool flex-align-center flex-justify-between">
      <input class="input" type="text" placeholder="请输入消息" v-model="message" />
      <div class="button" @click="sendMsg">发送消息</div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
const msgList = ref([])
watch(
  //这个时候不能用.value且必须是深度监听，这种写法不仅可以监听数组本身的变化，也可以监听 数组元素的变化
  msgList,
  () => {
    console.log('空数组变化了')
  },
  {
    deep: true
  }
)
msgList.value = [
  {
    sender: 'user1',
    reveiver: 'user2',
    msg: '消息消息'
  },
  {
    sender: 'user1',
    reveiver: 'user2',
    msg: '消息消息'
  },
  {
    sender: 'user1',
    reveiver: 'user2',
    msg: '消息消息'
  },
  {
    sender: 'user1',
    reveiver: 'user2',
    msg: '消息消息'
  }
]

const message = ref('')

const sendMsg = () => {
  msgList.value.push({
    sender: 'user1',
    reveiver: 'user2',
    msg: message.value
  })
  message.value = ''
  nextTick(() => {
    console.log('1')
    document.querySelector('.msg-content').scrollTop = 0
  })
}
</script>

<style lang="scss">
.msg-container {
  border: 1px solid #ededed;
  height: calc(100vh - 90px);
  width: 100%;
  position: relative;
  .msg-header {
    height: 60px;
    border-bottom: 1px solid #ededed;
    padding: 10px;
  }
  .msg-tool {
    width: 100%;
    height: 60px;
    border-top: 1px solid #ededed;
    padding: 10px;
    position: absolute;
    bottom: 0;
    gap: 20px;
    .button {
      border: 1px solid #deac21;
      background-color: #deac21;
      color: #fff;
      padding: 2px 10px;
      border-radius: 5px;
      cursor: pointer;
    }
    .input {
      flex: 2;
      width: 100%;
      height: 40px;
      padding: 2px 5px;
    }
  }
  .msg-content {
    height: calc(100% - 120px);
    padding: 10px;
    overflow-y: scroll;
    overflow-x: hidden;
    display: flex;
    flex-direction: column-reverse;
    .msg-box {
      display: flex;
      flex-direction: column;
      flex: 1 1;
      .msg-list {
        display: flex;
        flex-direction: column;
        gap: 10px;
        .msg-item {
          padding: 4px 10px;
          border-radius: 5px;
          background-color: #d1d1d1;
        }
      }
      .empty-box {
        flex-grow: 1;
      }
    }
  }
}
.flex-align-center {
  display: flex;
  align-items: center;
}
.flex-justify-end {
  display: flex;
  justify-content: flex-end;
}
.flex-justify-between {
  display: flex;
  justify-content: space-between;
}
</style>
